#include "users.h"

// 构造函数：自动去除输入空格
User::User(const QString& phone, const QString& password, const QString& address)
    : phone(phone.trimmed()), password(password.trimmed()), address(address.trimmed()) {}

// Getter方法
QString User::getPhone() const { return phone; }
QString User::getPassword() const { return password; }
QString User::getAddress() const { return address; }

// Setter方法：自动去除空格
void User::setPhone(const QString& phone) { this->phone = phone.trimmed(); }
void User::setPassword(const QString& password) { this->password = password.trimmed(); }
void User::setAddress(const QString& address) { this->address = address.trimmed(); }

// 数据完整性检查（非空验证）
bool User::isValid() const {
    return !phone.isEmpty() && !password.isEmpty() && !address.isEmpty();
}

// 密码一致性检查
bool User::isPasswordMatch(const QString& confirmPassword) const {
    return password == confirmPassword.trimmed();
}

// 手机号格式验证（简单11位校验）
bool User::isPhoneValid() const {
    QRegularExpression regex("^1[0-9]{10}$");//第一位必须是1
    return regex.match(phone).hasMatch();
}

//用户是否存在
bool User::userExists(const QString& phone, const QString& filename) {
    QFile file(filename);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file);
        while (!in.atEnd()) {
            QString line = in.readLine();
            QStringList fields = line.split("|");
            if (fields.size() >= 1 && fields[0] == phone.trimmed()) {
                file.close();
                return true;
            }
        }
        file.close();
    }
    return false;
}

// 保存用户数据到文件（追加模式）
bool User::saveToFile(const User& user, const QString& filename) {
    QFile file(filename);
    if (file.open(QIODevice::Append | QIODevice::Text)) {
        QTextStream out(&file);
        out << user.phone << "|" << user.password << "|" << user.address << "\n";
        file.close();
        return true;
    }
    return false;
}

// 从文件加载用户数据
User User::loadFromFile(const QString& phone, const QString& filename) {
    QFile file(filename);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file);
        while (!in.atEnd()) {
            QString line = in.readLine();
            QStringList fields = line.split("|");
            if (fields.size() >= 3 && fields[0] == phone) {
                file.close();
                return User(fields[0], fields[1], fields[2]);
            }
        }
        file.close();
    }
    return User(); // 返回空对象表示未找到
}

bool User::updateAddress(const QString &phone, const QString &newAddress, const QString &filename) {
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return false; // 文件打开失败
    }

    // 读取所有用户数据
    QList<User> users;
    QTextStream in(&file);
    while (!in.atEnd()) {
        QString line = in.readLine().trimmed();
        if (line.isEmpty()) continue;
        QStringList fields = line.split("|");
        if (fields.size() >= 3) {
            User user(fields[0].trimmed(), fields[1].trimmed(), fields[2].trimmed()); // 统一trim
            users.append(user);
        }
    }
    file.close(); // 显式关闭文件

    // 查找并更新用户
    bool found = false;
    for (auto &user : users) {
        if (user.getPhone() == phone.trimmed()) { // 统一trim比较
            user.setAddress(newAddress.trimmed());
            found = true;
            break;
        }
    }

    if (!found) return false;

    // 重新以写入模式打开文件（清空内容）
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
        return false;
    }

    // 写入更新后的数据
    QTextStream out(&file);
    for (const User &user : users) {
        out << user.getPhone() << "|" << user.getPassword() << "|" << user.getAddress() << "\n";
    }
    file.close();
    return true;
}
